import React, { Component } from 'react'

export default class FormCom extends Component {
    constructor() {
        super();
        this.state = {
            name: "jack",
            selectValue: "orange",
            inputOne: "",
            inputTwo: ""
        }
    }
    render() {
        let { name, selectValue, inputOne, inputTwo } = this.state;
        return (
            <>
                <form onSubmit={this.submit.bind(this)}>
                    {/* 受控组件 */}
                    <input type="text" value={name} onChange={(e) => { this.changeValue(e) }} />
                    <input type="submit" value="提交" />
                    <br />
                    <select value={selectValue} onChange={(e) => { this.changeSelect(e) }}>
                        <option value="apple">apple</option>
                        <option value="orange">orange</option>
                        <option value="good">good</option>
                    </select>
                    {/* 其它情况类似 */}
                    {/* <input type="checkbox"/> checked = {Boolean} onChange event.target.checked
                    <input type="radio"/> checked = {Boolean} onChange event.target.checked
                    <textarea name="" id="" cols="30" rows="10"></textarea> value={string} onChange event.target.value */}

                    {/* 处理多个输入的情况 */}
                    <input type="text" name="inputOne" value={inputOne} onChange={(e) => {this.changeInput(e)}}/>
                    <input type="text" name="inputTwo" value={inputTwo} onChange={(e) => {this.changeInput(e)}}/>

                    {/* 非受控组件，使用ref获取DOM元素 */}
                    <input type="text"  defaultValue="默认值" ref = "inputValue"/>
                </form>

            </>
        )
    }
    changeValue(e) {
        this.setState({
            name: e.target.value
        })
    }
    changeSelect(e) {
        this.setState({
            selectValue: e.target.value
        })
    }
    changeInput(e) {
        this.setState({
            [e.target.name]: e.target.value
        })
    }
    submit(e) {
        console.log(this.state);
        console.log(this.refs.inputValue.value);
        // 这里阻止默认事件不能使用return false;
        e.preventDefault();
    }
}
